package com.zhan.rkforum.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author wujiazhan
 * @className Md5Util
 * @description TODO
 * @date 2021-05-27 23:52
 */
@Component
public class CommunityUtil {
    /**
     * 加密生成Md5字符串
     * @param string 被加密的字符串
     * @return Map<String, String> 盐值和加密字符串的map集合
     */
    public static Map<String, String> parseByMd5(String string){
        //长度为8的盐值
        String salt = UUID.randomUUID().toString().replace("-","").substring(0,7);
        HashMap<String, String> map = new HashMap<>();
        String s = parseByMd5(string, salt);
        map.put("salt", salt);
        map.put("md5String",s);
        return map;
    }


    // MD5加密
    // hello -> abc123def456
    // hello + 3e4a8 -> abc123def456abc
    public static String parseByMd5(String key,String salt) {
        if (StringUtils.isBlank(key) || StringUtils.isBlank(salt)) {
            return null;
        }
        return DigestUtils.md5DigestAsHex((key+salt).getBytes());
    }

    /**
     * uuid生成随机字符串
     *
     * @return {@link String}
     */
    public static String generateUuid(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 将结果信息转化为json字符串
     *
     * @param code 状态码
     * @param msg  结果信息
     * @param map  结果集
     * @return {@link String}
     */
    public static String getJsonString(int code, String msg, Map<String, Object> map){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg",msg);
        jsonObject.put("map",map);
        return jsonObject.toJSONString();
    }
    //重载
    public static String getJsonString(int code, String msg) {
        return getJsonString(code, msg, null);
    }
    //重载
    public static String getJsonString(int code) {
        return getJsonString(code, null, null);
    }
}
